//
//  HDAnnotationView.m
//  HDMapKit
//
//  Created by Liuzhuan on 13-4-8.
//  Copyright (c) 2013年 hengdawb. All rights reserved.
//

#import "HDAnnotationView.h"
#import "HDCallOutView.h"
#import <QuartzCore/QuartzCore.h>
#import "UIButton+WebCache.h"
#import "HD_NKM_MapView.h"

@implementation HDAnnotationView
{
    HDDeclare *declare;
}
#define RED_PIN             @"map_location_A"
#define PIN_WIDTH           35.0  // POI图片大小，根据实际填写
#define PIN_HEIGHT          40.0

#define PIN_POINT_X         8.0
#define PIN_POINT_Y         35.0
#define CALLOUT_OFFSET_X    7.0
#define CALLOUT_OFFSET_Y    5.0

#pragma mark
#pragma mark -------- Init Methods --------

- (instancetype)initWithAnnotation:(HDAnnotation *)annotation onView:(HD_NKM_MapView *)mapView animated:(BOOL)animate {
	CGRect frame = CGRectMake(0, 0, 0, 0); // TODO: remove this
    
	if ((self = [super initWithFrame:frame])) {
		self.annotation = annotation;
        declare = [HDDeclare sharedDeclare];
        self.frame      = [self frameForPoint:self.annotation.point];
        
        UIImage *myImage = [UIImage imageNamed:RED_PIN];
        [self setImage:myImage forState:UIControlStateNormal];
//        [self sd_setImageWithURL:[NSURL URLWithString:annotation.poiImgPath] forState:UIControlStateNormal placeholderImage:myImage];

        UIEdgeInsets edgeInset = UIEdgeInsetsMake(PIN_HEIGHT/6, PIN_WIDTH/6, PIN_HEIGHT/6, PIN_WIDTH/6);
        self.contentEdgeInsets = edgeInset;
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
		[self addTarget:mapView action:@selector(showCallOut:) forControlEvents:UIControlEventTouchDown];
        self.enabled = YES;
        
		[mapView addSubview:self];
	}
    
	return self;
}

- (void)setClusterCount:(NSInteger)clusterCount{
    _clusterCount = clusterCount;
    [self setImage:nil forState:UIControlStateNormal];
    [self setTitle:[NSString stringWithFormat:@"%ld",clusterCount] forState:UIControlStateNormal];
    if (clusterCount > 1) {
        
        [self.superview bringSubviewToFront:self];
    }
//    if (clusterCount > 1) {
//    }else{
//        self.backgroundColor = [UIColor clearColor];
//        UIImage *myImage = [UIImage imageNamed:RED_PIN];
//        [self setImage:myImage forState:UIControlStateNormal];
//        _clusterCount = 1;
//    }
}

- (void)bigPicture
{
    [self.layer removeAnimationForKey:@"scale-layer"];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    CGFloat pointScale = 2.0f;

    // 动画选项设定
    animation.duration = 0; // 动画持续时间
    animation.repeatCount = NSIntegerMax; // 重复次数
    animation.autoreverses = YES; // 动画结束时执行逆动画
    
    // 缩放倍数
    animation.fromValue = [NSNumber numberWithFloat:pointScale]; // 开始时的倍率
    animation.toValue = [NSNumber numberWithFloat:pointScale];   // 结束时的倍率
    [self.layer addAnimation:animation forKey:@"scale-layer"];
}

- (void)smallPicture
{
    [self.layer removeAnimationForKey:@"scale-layer"];
}

- (void)beginAnimate
{
    CGFloat originY = 0;
    CGFloat originX = self.imageView.frame.origin.x;
    CGFloat width = self.imageView.frame.size.width;
    CGFloat height = self.imageView.frame.size.height;
    
    if (upOrdown == NO) {
        num --;
        self.imageView.frame = CGRectMake(originX, originY+num, width, height);
        if (num == -5) {
            upOrdown = YES;
        }
    }
    else {
        num ++;
        self.imageView.frame = CGRectMake(originX, originY+num, width, height);
        if (num == 0) {
            upOrdown = NO;
        }
    }
}

- (void)stopAnimate
{
    self.imageView.frame = CGRectMake(self.imageView.frame.origin.x, 0, self.imageView.frame.size.width, self.imageView.frame.size.height);

    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(beginAnimate) object:nil];
    [_timer invalidate];
    self.timer = nil;
}

- (void)locationChangeCenter:(CGPoint)point {
    
    CGFloat x = point.x - PIN_POINT_X;
    CGFloat y = point.y - PIN_POINT_Y;
    // 减去10是要扩大手势范围
    self.frame = CGRectMake(round(x)-10, round(y)-10, PIN_WIDTH, PIN_HEIGHT);
}

- (CGRect)frameForPoint:(CGPoint)point {
    
    CGFloat x = point.x - PIN_WIDTH/2;
    CGFloat y = point.y - PIN_HEIGHT/2;
    
    return CGRectMake(round(x), round(y), PIN_WIDTH, PIN_HEIGHT);
}

/*- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
	if ([keyPath isEqual:@"contentSize"]) {
		HDMapView *mapView = (HDMapView *)object;
		CGFloat      width   = (mapView.contentSize.width / mapView.orignalSize.width/mapView.minimumZoomScale) * self.annotation.point.x;
        CGFloat      height  = (mapView.contentSize.height / mapView.orignalSize.height/mapView.minimumZoomScale) * self.annotation.point.y;
		
		self.frame = [self frameForPoint:CGPointMake(width, height)];
	}
}*/

// 对mapview的放大倍数增加观察者，所有的POI根据放大倍数动态调整坐标
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqual:@"contentSize"]) {
        HD_NKM_MapView *mapView = (HD_NKM_MapView *)object;
        CGFloat      width   = (mapView.contentSize.width / mapView.orignalSize.width/mapView.minimumZoomScale) * self.annotation.point.x;
        CGFloat      height  = (mapView.contentSize.height / mapView.orignalSize.height/mapView.minimumZoomScale) * self.annotation.point.y;
        self.frame = [self frameForPoint:CGPointMake(width, height)];
        if (_annotation.isPlay == kPlay_Status_Successive) // 不针对连续定位点
        {
            return;
        }
        
        // 根据放大倍数的不同，修改POI图片的放大倍数
        CGFloat zoomScale = mapView.zoomScale;
        CGFloat pointScale = 1.0f;
        CGFloat valuse = -PIN_HEIGHT/100 * zoomScale;
        if (zoomScale <= mapView.minimumZoomScale+0.00001) {
            valuse = PIN_HEIGHT/6;
            pointScale = 1.0f;
        }
        else if (zoomScale >= 5) {
            valuse = 0;
            pointScale = 2.0f;
        }
        else if (zoomScale >= 4) {
            valuse = -PIN_HEIGHT/16;
            pointScale = 1.6f;
        }
        else if (zoomScale >= 2) {
            valuse = PIN_HEIGHT/8;
            pointScale = 1.3f;
        }
    }
}

// 语音播放后，更新地图上对应POI的图片，
// 或者是收号以后，更新，图片传入的是路径
- (void)changePOIImageWithPath:(NSString *)imgPath
{
    if (self.annotation.isPlay == kPlay_Status_No)
    { self.annotation.isPlay = kPlay_Status_Yes; }
    else if (self.annotation.isPlay == kPlay_Status_More)
    { self.annotation.isPlay = kPlay_Status_More_Read; }
    
    UIImage *myImage = [UIImage imageWithContentsOfFile:imgPath];
    if (myImage == nil)
        myImage = [UIImage imageNamed:RED_PIN];
    
    [self setImage:myImage forState:UIControlStateNormal];
}

- (void)dealloc
{
    [self stopAnimate];
    _annotation = nil;
}

@end
